import {
	getToken,
	removeToken,
	removeUserInfo
} from '@/utils/auth'
import {
	toast,
	showConfirm,
	tansParams
} from '@/utils/common'
import {
	encryptBase64,
	encryptWithAes,
	generateAesKey,
	decryptWithAes,
	decryptBase64
} from '@/utils/crypto';
import {
	encrypt,
	decrypt
} from '@/utils/jsencrypt';
let timeout = 60000
import env from "@/env.js";
const baseUrl = env.url

const encryptHeader = 'encrypt-key';

const request = config => {
	// 是否需要加密
	const isEncrypt = config.headers ? config.headers.isEncrypt : false

	// 是否需要设置 token
	const isToken = (config.headers || {}).isToken === false
	config.header = config.headers || {}
	if (getToken() && !isToken) {
		config.header['Authorization'] = getToken()
	}
	// get请求映射params参数
	if (config.params) {
		let url = config.url + '?' + tansParams(config.params)
		url = url.slice(0, -1)
		config.url = url
	}

	if (baseUrl == 'https://www.hnthht.com/stage-api') {
		if (isEncrypt && (config.method === 'post' || config.method === 'put')) {
			// 生成一个 AES 密钥
			const aesKey = generateAesKey();
			config.headers[encryptHeader] = encrypt(encryptBase64(aesKey));
			config.data = typeof config.data === 'object' ? encryptWithAes(JSON.stringify(config.data), aesKey) :
				encryptWithAes(config.data, aesKey);
		}
	}

	return new Promise((resolve, reject) => {
		uni.request({
				method: config.method || 'get',
				timeout: config.timeout || timeout,
				url: config.baseUrl || baseUrl + config.url,
				data: config.data,
				header: config.header,
				dataType: 'json'
			}).then(res => {
				if (res.statusCode == 200) {
					// 加密后的 AES 秘钥

					const keyStr = res.header[encryptHeader];
					// 加密
					if (keyStr != null && keyStr != '') {
						const data = res.data;
						// 请求体 AES 解密
						const base64Str = decrypt(keyStr);
						// base64 解码 得到请求头的 AES 秘钥
						const aesKey = decryptBase64(base64Str.toString());
						// aesKey 解码 data
						const decryptData = decryptWithAes(data, aesKey);
						// 将结果 (得到的是 JSON 字符串) 转为 JSON
						res.data = JSON.parse(decryptData);
					}


					// 接口0成功，根据需要调整
					if (res.data.code == 200) {
						resolve(res.data)
					} else if (res.data.code == 401) {
						//清除用户登录数据和token
						removeUserInfo()
						removeToken()
						uni.showToast({
							icon: 'none',
							duration: 2000,
							title: '登录过期，请重新登录',
							success() {

							}
						})
						setTimeout(function() {
							uni.reLaunch({
								url: '/pages/login/login'
							})
						}, 1000);
					} else {
						toast(res.data.msg)
						// reject(code)
					}
				} else {
					uni.showToast({
						title: '网络开小差了，请稍后再试',
						icon: 'none',
						duration: 2000
					})
				}
			})
			.catch(error => {
				uni.showToast({
					title: '网络开小差了，请稍后再试',
					icon: 'none',
					duration: 2000
				})
				reject(error)
			})
	})
}

export default request